package Parsers::Phenyx;

use strict;
use warnings;

my $VERSION = '1.00';
our @EXPORT_OK = qw();
use base qw(Exporter);

use Spreadsheet::ParseExcel;



sub analyze{
	my @phenyx_files = @_;
	my %info_phenyx;
	my %spec_zscore;

	#Parseo todos los xls de phenyx que se van a juntar
	foreach(@phenyx_files){
		my %parsed_phenyx = parse($_);
		foreach(keys %parsed_phenyx){
			$info_phenyx{$_} = $parsed_phenyx{$_};
			$spec_zscore{$_} = $info_phenyx{$_}{'zscore'};
		}
	}
	return %info_phenyx;
}

sub parse{
	my $phenyx_file = shift;            #Excel worksheet global export
	my %phenyx;
	my @lineas;
	my $num_linea = 0;
	my $encabezamiento = "";

	my $parser = Spreadsheet::ParseExcel->new();
	my $workbook = $parser->parse($phenyx_file);

	for my $sheet ($workbook->worksheets()) {
		if ($sheet->{Name} eq 'MSMS Matches'){
			my ($row_min, $row_max) = $sheet->row_range();
			my ($col_min, $col_max) = $sheet->col_range();
			for my $row ($row_min .. $row_max) {
				for my $col ($col_min .. $col_max) {
					my $cell = $sheet->get_cell($row, $col);
					$lineas[$row][$col] = $cell->value() if($cell);
				}
			}
		}
	}

	#si la primera columna de la primera linea
	#no contiene 'Compound', no se parsea nada.
	unless($lineas[0][0] =~ /^Compound/){return;}

	for (1..$#lineas){
		my @cols = @{$lineas[$_]};
		my $compound_description;
		if($cols[0]){$compound_description = $cols[0]} else {$compound_description = ''};
		#Descompongo Compound description en sus componentes
		#Eritrocitos_FASP_OGE_TiO2_Fr04,Scan:1108,MS:3,Rt:1913.337
		my ($espectro, $scan, $ms, $rt) = split /\,/, $compound_description;
		$scan =~ s/Scan\://;
		my ($scan1, $scan2);
		if($scan =~ /\-/){                 #si contiene un guion
			($scan1, $scan2) = split /\-/, $scan;
		}
		else{
			($scan1, $scan2) = ($scan, $scan);
		}
		$ms =~ s/MS\://;
		$rt =~ s/Rt\://;
		$rt = sprintf("%.0f", $rt);
		my $spectrum_key = $espectro . '.' . $scan1 . '.' . $scan2;

		my $zscore;
		if($cols[8]){$zscore = $cols[8]} else {$zscore = ''};
		#Si ya existe, solo me quedo (sobreescribo con) el de zscore mayor
		if(defined $phenyx{$spectrum_key}){
			if($phenyx{$spectrum_key}{'zscore'} > $zscore){
				next;
			}
		}

		my $validity;
		if($cols[1]){$validity = $cols[1]} else {$validity = ''};

		my $sequence;
		if ($cols[13]){$sequence = $cols[13]} else {$sequence = ''};

		my $z;
		if ($cols[5]){$z = $cols[5]} else {$z = ''};

		my $mz;
		if ($cols[6]){$mz = $cols[6]} else {$mz = ''};

		my $deltamz;
		if($cols[7]){$deltamz = $cols[7]} else {$deltamz = ''};

		my $dbmatch;
		if($cols[12]){$dbmatch = $cols[12]} else {$dbmatch = ''};

		my @prots = split ' ', $dbmatch;
		my $first_prot = (split '%', $prots[0])[1];

		$phenyx{$spectrum_key}{'ms'} = $ms;
		$phenyx{$spectrum_key}{'rt'} = $rt;
		$phenyx{$spectrum_key}{'validity'} = $validity;

		($phenyx{$spectrum_key}{'unmodified_sequence'},
		 $phenyx{$spectrum_key}{'modified_sequence'}
		) = convierte_cadena_phenyx($sequence);

		#Elimino modificacion en la C (CAM, unimod code: 4)
		$phenyx{$spectrum_key}{'modified_sequence'}=~s/\(4\)//g;
		$phenyx{$spectrum_key}{'z'} = $z;
		$phenyx{$spectrum_key}{'mz'} = $mz;
		$phenyx{$spectrum_key}{'deltamz'} = $deltamz;
		$phenyx{$spectrum_key}{'zscore'} = $zscore;
		$phenyx{$spectrum_key}{'db_first_match'} = $first_prot;
		$phenyx{$spectrum_key}{'count'} = 1 + $#prots;
	}
	return %phenyx;
}

sub convierte_cadena_phenyx{
	my $cadena = shift;
	# $cadena --> "YISPDQLADLYK%:iTRAQ_Y:::::::::::iTRAQ_K:%sample_1%cmpd_314"
	my $cad_sin_mod = (split /\%/, $cadena)[0];
	my $modifs = (split /\%/, $cadena)[1];
	my @aas = split //, $cad_sin_mod;
	push @aas, '';                           #para recoger la ultima modificacion
	my @mods = split ':', $modifs;

	my $cadena_modif = '';
	for(0..$#aas){
		if($mods[$_]){
			$mods[$_]=~s/Cys_CAM/\(4\)/;
			$mods[$_]=~s/Oxidation_M/\(35\)/;
			$mods[$_]=~s/PHOS/\(21\)/;
			$mods[$_]=~s/deshidratacionST/\(23\)/;
			$mods[$_]=~s/iTRAQ_K/\(214\)/;
			$mods[$_]=~s/iTRAQ_Y/\(214\)/;
			$mods[$_]=~s/iTRAQ_Nterm/\(214\)/;
			$mods[$_]=~s/TMTsixplex_K/\(737\)/;
			$mods[$_]=~s/TMTsixplex_Y/\(737\)/;
			$mods[$_]=~s/TMTsixplex_Nterm/\(737\)/;

			$cadena_modif = $cadena_modif . $mods[$_];
		}
		$cadena_modif = $cadena_modif . $aas[$_];
	}
	#modif nt la cambio de izquierda a derecha del primer aa
	$cadena_modif =~s/^\(214\)(.)/$1\(214\)/;
	$cadena_modif =~s/^\(737\)(.)/$1\(737\)/;

	#si hay dos modificaciones consecutivas en nt, las unifico: (x)(y)->(x,y)
	$cadena_modif =~s/^(\w)\((\d+)\)\((\d+)\)/$1\($2\,$3\)/;

	return ($cad_sin_mod, $cadena_modif);
}


1;   #167


__END__

=head1 NAME

=head1 SYNOPSIS

=head1 DESCRIPTION

=head1 LIMITATIONS

=head1 SEE ALSO

=cut
